﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Common.Model;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json.Linq;
using pinduoduo.Model;
using pinduoduo.Util;
using System.Linq;
using Sunny.UI;
using Tk.Soc.Share.Common.Helpers;
using pinduoduo.CefHandler;

namespace pinduoduo.From
{
    public partial class BrowserGoodId : UIForm
    {

        private ChromiumWebBrowser AccountChromeBrowser;

        private RequestContext AccountContext;

        public Action UpdateGoodInfoAction;
        public Action<string> SetGoodIdAction;

        private string url;
        private string daili;

        public BrowserGoodId(string url,PddToken pddToken=null)
        {
            this.url = url;
             
            InitializeComponent();
            InitializeAccountChromium(pddToken);
         
            AccountChromeBrowser.Load(url);
            //if (pddToken != null) 
            //{
            //    SetToken(pddToken);
            //}
        }

        async private void SetProxy(ChromiumWebBrowser cwb, string Address)
        {
            await Cef.UIThreadTaskFactory.StartNew(delegate
            {
                var rc = cwb.GetBrowser().GetHost().RequestContext;
                var v = new Dictionary<string, string>();
                v["mode"] = "fixed_servers";
                v["server"] = Address;
                string error;
                bool success = rc.SetPreference("proxy", v, out error);
                if (!string.IsNullOrWhiteSpace(error))
                {
                    MessageBox.Show(error, "Tip", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });

        }
   

        async void SetToken(PddToken pddToken) 
        {
            await AccountContext.GetCookieManager(null).DeleteCookiesAsync(pddurl, "PDDAccessToken");
            await AccountContext.GetCookieManager(null).DeleteCookiesAsync(pddurl, "pdd_user_id");

            var PDDAccessToken = new CefSharp.Cookie
            {
                Path = "/",
                Domain = "yangkeduo.com",
                Creation = DateTime.Today,
                Expires = DateTime.Today.AddDays(30),
                Name = "PDDAccessToken",
                Value = pddToken.PDDAccessToken
            };
            var pdd_user_id = new CefSharp.Cookie
            {
                Path = "/",
                Domain = "yangkeduo.com",
                Creation = DateTime.Today,
                Expires = DateTime.Today.AddDays(30),
                Name = "pdd_user_id",
                Value = pddToken.pdd_user_id
            };
            await AccountContext.GetCookieManager(null).SetCookieAsync(pddurl, pdd_user_id);
            await AccountContext.GetCookieManager(null).SetCookieAsync(pddurl, PDDAccessToken);
        }

        private void AutoPayFrom_Load(object sender, EventArgs e)
        {

        }

        //初始化浏览器并启动
        public void InitializeAccountChromium(PddToken pddToken)
        {

            AccountContext = new RequestContext(new RequestContextSettings()
            {
                CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\global3\\",
                PersistSessionCookies = false,
                PersistUserPreferences = false
            });
            SetToken(pddToken);
            AccountChromeBrowser = new ChromiumWebBrowser("http://www.baidu.com", AccountContext);
            //AccountChromeBrowser.RequestHandler = new ProxyAuthRequestHandler();
            AccountChromeBrowser.RequestContext = AccountContext;
            BrowserSettings browserSettings = new BrowserSettings();
            browserSettings.ApplicationCache = CefState.Enabled;

            AccountChromeBrowser.BrowserSettings = browserSettings;

#if DEBUG
            AccountChromeBrowser.KeyboardHandler = new CEFKeyBoardHander();
#endif
            this.panel1.Controls.Add(AccountChromeBrowser);


            AccountChromeBrowser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;

            AccountChromeBrowser.Dock = DockStyle.Fill;
        }

        private void OnIsBrowserInitializedChanged(object sender, EventArgs args)
        {
            //SetProxy(AccountChromeBrowser, daili);
        }

        private string pddurl = "http://yangkeduo.com/";

        public async void SetCookie(RequestContext AccountContext)
        {
            List<CefSharp.Cookie> cookies = await AccountContext.GetCookieManager(null).VisitUrlCookiesAsync(pddurl, true);

            foreach (var item in cookies)
            {
                await AccountChromeBrowser.GetCookieManager().SetCookieAsync(pddurl, item);
            }
        }

        private async void GetNetGoodButton_Click(object sender, EventArgs e)
        {
            string script = @"(function() { return  window.rawData.store.initDataObj;})()";

            await AccountChromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
            {
                var response = x.Result;

                if (response.Success && response.Result != null)
                {
                    var jo = JObject.FromObject(response.Result);
                    try
                    {
                        var goods_id = jo["queries"]["goods_id"].ToString();


                        var _oc_n_mkt_tr_token = jo["queries"]["_oc_n_mkt_tr_token"].ToString();
                        var _oc_n_mkt_domain = jo["queries"]["_oc_n_mkt_domain"].ToString();
                        var _oc_n_mkt_tr_sc = jo["queries"]["_oc_n_mkt_tr_sc"].ToString();
                        var _oc_live_show_id = jo["queries"]["_oc_live_show_id"].ToString();
                        var refer_page_name = jo["queries"]["refer_page_name"]?.ToString();
                        var refer_page_id = jo["queries"]["refer_page_id"]?.ToString();
                        var refer_page_sn = jo["queries"]["refer_page_sn"]?.ToString();

                        PddGood pddGood = new PddGood();
                        pddGood.good_id = goods_id;
                        pddGood.type = (int)PddGoodSource.ZhiBo;
                        pddGood.live_show_id = _oc_live_show_id;
                        pddGood.mkt_domain = _oc_n_mkt_domain;
                        pddGood.mkt_tr_sc = _oc_n_mkt_tr_sc;
                        pddGood.mkt_tr_token = _oc_n_mkt_tr_token;

                        pddGood.refer_page_id = refer_page_id;
                        pddGood.refer_page_name = refer_page_name;
                        pddGood.refer_page_sn = refer_page_sn;

                        var groupTypes = jo["goods"]["groupTypes"];
                        if (groupTypes.Count() > 0)
                        {
                            pddGood.gID2 = groupTypes[0]["groupID"].ToString();
                        }
                        if (groupTypes.Count() > 1)
                        {
                            pddGood.gID1 = groupTypes[1]["groupID"].ToString();
                        }

                        var skus = jo["goods"]["skus"];
                        string skuJson = JsonHelper.SerializeObject(skus);
                        pddGood.sku = skuJson;


                        PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goods_id);
                        if (pdd == null)
                        {
                            long reslut = DataBaseHelper.SqLiteDBCon.Insert(pddGood);
                        }
                        else
                        {
                            pddGood.SourceKeywords = pdd.SourceKeywords;

                            DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
                        }
                        this.BeginInvoke(new Action(() =>
                        {
                            SetGoodIdAction?.Invoke(goods_id);
                            UpdateGoodInfoAction?.Invoke();
                            //MessageBox.Show("获取数据成功");
                            ShowSuccessNotifier("获取数据成功");
                        }));

                    }
                    catch
                    {
                        ShowErrorNotifier("获取数据失败");
                    }
                }
                return;
            });
        }
    }
}
